package org.example.gradleauth.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import gradle.common.core.constants.MediaType;
import gradle.common.core.response.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

/**
 * FailureHandler
 *
 * @author 1141193930@qq.com
 */
public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        ApiResponse<Object> error = ApiResponse.error(HttpServletResponse.SC_BAD_REQUEST, exception.getMessage());

        if (exception instanceof LockedException) {

            error = ApiResponse.error(HttpServletResponse.SC_BAD_REQUEST, "账号已被锁定！");

        } else if (exception instanceof DisabledException) {

            error = ApiResponse.error(HttpServletResponse.SC_BAD_REQUEST, "账号已被禁用！");

        }

        response.getWriter().write(mapper.writeValueAsString(error));
    }
}